<?php
  // Requires Facebook PHP SDK 3.0.1: https://github.com/facebook/php-sdk/
  require ('includes/facebook.php');

  define('FACEBOOK_APP_ID',"160596754040030");
  define('FACEBOOK_SECRET',"20ea9c13cac64e709f346cac489669f9");

  $user = null;

  // Create our Application instance (replace this with your appId and secret).
  $facebook = new Facebook(array(
  'appId' => FACEBOOK_APP_ID,
  'secret' => FACEBOOK_SECRET,
  'cookie' => true
  ));

  $user = $facebook->getUser();
  $loginUrl = $facebook->getLoginUrl();

  if ( empty($user) ) {
    echo("<script> top.location.href='" . $loginUrl . "'</script>");
    exit();
  }
?>
<!doctype html>
<html>
  <head>
    <title>How To: Send An Application Request Using The Facebook Graph API - MasteringAPI.com</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

  </head>
  <body>
    <div id="fb-root"></div>


    <a href="#">Send Application Request</a>

    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId: '<?php echo $facebook->getAppID() ?>',
          status: true,
          cookie: true,
          oauth: true
        });
      };

      $('a').click(sendRequest);
      function sendRequest() {
        FB.ui({
          method: 'apprequests',
          message: 'Check out this application!',
          title: 'Send your friends an application request',
        },
        function (response) {
          if (response.request && response.to) {
            var request_ids = [];
            for(i=0; i<response.to.length; i++) {
              var temp = response.request + '_' + response.to[i];
              request_ids.push(temp);
            }
            var requests = request_ids.join(',');
            $.post('handle_requests.php',{uid: '<?php echo $user; ?>', request_ids: requests},function(resp) {
              // callback after storing the requests
            });
          } else {
            alert('canceled');
          }
        });
        return false;
      }

      // Load the SDK Asynchronously
      (function(d){
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
      }(document));
    </script> 
  </body>
</html>